<template>
	<view class="profit-prediction-container" :style="containerStyle">

		<!-- 顶部导航栏 -->
		<nav-bar title="盈亏预测" />

		<!-- 页面头部区域 -->
		<view class="page-header">
			<!-- 项目信息提示 -->
			<view v-if="projectId" class="project-info-bar">
				<view class="project-info-content">
					<view class="info-icon">📋</view>
					<view class="info-text">
						<text class="project-label">当前项目</text>
						<text class="project-name-text">{{ projectName }}</text>
					</view>
				</view>
			</view>

			<!-- 选项卡导航 -->
			<view class="tabs">
				<view class="tab" :class="{ active: activeTab === 'input' }" @tap="activeTab = 'input'">
					<view class="tab-content">
						<text class="tab-icon">📝</text>
						<text class="tab-text">信息录入</text>
					</view>
					<view class="tab-indicator" v-if="activeTab === 'input'"></view>
				</view>
				<view class="tab" :class="{ active: activeTab === 'result' }" @tap="activeTab = 'result'">
					<view class="tab-content">
						<text class="tab-icon">📊</text>
						<text class="tab-text">分析结果</text>
					</view>
					<view class="tab-indicator" v-if="activeTab === 'result'"></view>
				</view>
			</view>
		</view>

		<!-- 输入区域包装器 -->
		<scroll-view scroll-y class="input-wrapper" v-if="activeTab === 'input'">
			<!-- 投资金额卡片 -->
			<view class="section-card">
				<view class="section-header">
					<view class="icon-container">🏢</view>
					<text class="section-title">投资金额</text>
					<text class="summary-value">{{ formatCurrency(totalInvestmentCost) }}</text>
				</view>
				<view class="input-group-grid">
					<view class="input-field">
						<text class="field-label">设备费用 (元)</text>
						<input type="number" v-model="inputFormData.equipmentCost" class="form-input" min="0">
					</view>
					<view class="input-field">
						<text class="field-label">装修费用 (元)</text>
						<input type="number" v-model="inputFormData.renovationCost" class="form-input" min="0">
					</view>
					<!-- 首批采购成本 (元) -->
					<view class="input-field">
						<text class="field-label">首批采购成本 (元)</text>
						<input type="number" v-model="inputFormData.firstPurchaseCost" class="form-input" min="0">
					</view>
				</view>

			</view>

			<!-- 运营成本卡片 -->
			<view class="section-card">
				<view class="section-header">
					<view class="icon-container">💼</view>
					<text class="section-title">月运营成本</text>
					<text class="summary-value">{{ formatCurrency(totalMonthlyOperatingCost) }}</text>
				</view>
				<view class="input-group-grid">
					<view class="input-field">
						<text class="field-label">房租,物业费 (元)</text>
						<input type="number" v-model="inputFormData.rentAndPropertyCost" class="form-input" min="0">
					</view>
					<view class="input-field">
						<text class="field-label">员工工资 (元)</text>
						<input type="number" v-model="inputFormData.staffSalaryAndInsurance" class="form-input" min="0">
					</view>
					<view class="input-field">
						<text class="field-label">水电杂费 (元)</text>
						<input type="number" v-model="inputFormData.utilitiesAndMisc" class="form-input" min="0">
					</view>
					<view class="input-field">
						<text class="field-label">管理与营销费 (元)</text>
						<input type="number" v-model="inputFormData.managementAndMarketing" class="form-input" min="0">
					</view>
					<view class="input-field">
						<text class="field-label">贷款利息 (元)</text>
						<input type="number" v-model="inputFormData.loanInterest" class="form-input" min="0">
					</view>
					<view class="input-field">
						<text class="field-label">其他费用 (元)</text>
						<input type="number" v-model="inputFormData.otherCosts" class="form-input" min="0">
					</view>

				</view>

			</view>

			<!-- 品类毛利率与损耗率卡片 -->
			<view class="section-card">
				<view class="section-header">
					<view class="icon-container">📊</view>
					<text class="section-title">品类毛利率与损耗率</text>
				</view>

				<!-- 错误提示信息 -->
				<view v-if="validationErrors.ratio" class="error-message">
					<text class="error-icon">⚠️</text>
					<text class="error-text">{{ validationErrors.ratioMessage }}</text>
				</view>

				<view class="category-table">
					<view class="table-header">
						<text class="table-cell">品类</text>
						<text class="table-cell">销售占比(%)</text>
						<text class="table-cell">毛利率(%)</text>
						<text class="table-cell">损耗率(%)</text>
					</view>
					<view class="table-row">
						<text class="table-cell">蔬菜水果</text>
						<input type="number" v-model="inputFormData.vegetableRatio"
							:class="['table-input', { 'input-error': validationErrors.ratio }]" min="0" max="100"
							@input="handleRatioInput">
						<input type="number" v-model="inputFormData.vegetableMargin" class="table-input" min="0"
							max="100">
						<input type="number" v-model="inputFormData.vegetableLoss" class="table-input" min="0"
							max="100">
					</view>
					<view class="table-row">
						<text class="table-cell">肉类水产</text>
						<input type="number" v-model="inputFormData.meatRatio"
							:class="['table-input', { 'input-error': validationErrors.ratio }]" min="0" max="100"
							@input="handleRatioInput">
						<input type="number" v-model="inputFormData.meatMargin" class="table-input" min="0" max="100">
						<input type="number" v-model="inputFormData.meatLoss" class="table-input" min="0" max="100">
					</view>
					<view class="table-row">
						<text class="table-cell">干货粮油</text>
						<input type="number" v-model="inputFormData.dryRatio"
							:class="['table-input', { 'input-error': validationErrors.ratio }]" min="0" max="100"
							@input="handleRatioInput">
						<input type="number" v-model="inputFormData.dryMargin" class="table-input" min="0" max="100">
						<input type="number" v-model="inputFormData.dryLoss" class="table-input" min="0" max="100">
					</view>
					<view class="table-row">
						<text class="table-cell">日用品</text>
						<input type="number" v-model="inputFormData.dailyRatio"
							:class="['table-input', { 'input-error': validationErrors.ratio }]" min="0" max="100"
							@input="handleRatioInput">
						<input type="number" v-model="inputFormData.dailyMargin" class="table-input" min="0" max="100">
						<input type="number" v-model="inputFormData.dailyLoss" class="table-input" min="0" max="100">
					</view>
				</view>
				<view class="category-summary">
					<view class="summary-item">
						<text>综合毛利率: </text>
						<text class="summary-value">{{ realtimeCompositeMargin.toFixed(2) }}%</text>
					</view>
					<view class="summary-item">
						<text>平均损耗率: </text>
						<text class="summary-value">{{ realtimeAverageLoss.toFixed(2) }}%</text>
					</view>
				</view>
			</view>

			<!-- 经营数据输入区域 -->
			<view class="section-card">
				<view class="section-header">
					<view class="icon-container">📈</view>
					<text class="section-title">经营数据</text>
				</view>
				<view class="input-group">
					<view class="input-field">
						<text class="field-label">平均客单价 (元)</text>
						<input type="number" v-model="inputFormData.averagePrice" class="form-input" min="0">
						<text class="field-tip">生鲜行业常见范围：20-80元</text>
					</view>
					<view class="input-field">
						<text class="field-label">每月营业天数</text>
						<input type="number" v-model="inputFormData.businessDays" class="form-input" min="0" max="31">
					</view>
					<view class="input-field">
						<text class="field-label">预计客流</text>
						<input type="number" v-model="inputFormData.estimatedCustomers" class="form-input" min="0">
					</view>
				</view>
			</view>

			<!-- 操作按钮组 -->
			<view class="btn-group">
				<!-- 信息录入选项卡下的按钮 -->
				<template v-if="activeTab === 'input'">
					<button class="btn btn-secondary" @click="handleReset">清空数据</button>
					<button class="btn btn-primary" @click="handleAnalyzeAndSave">分析结果</button>
					<button class="btn btn-primary" @click="fillWithDemoData">模拟数据</button>
				</template>
			</view>

		</scroll-view>

		<!-- 结果区域 -->
		<scroll-view scroll-y class="results-section" v-if="activeTab === 'result'">
			<!-- ==================== 基础信息 ==================== -->

			<!-- 投资回报分析卡片 -->
			<view class="result-card highlight-card investment-card">
				<view class="result-header">
					<text class="result-title">💰 投资回报分析</text>
				</view>
				<view class="result-content">
					<!-- 总投资金额 - 居中显示 -->
					<view class="investment-total">
						<text class="investment-label">总投资金额</text>
						<text class="investment-amount">{{ formatCurrency(totalInvestmentCost) }}</text>
					</view>

					<!-- 投资构成明细 -->
					<view class="investment-breakdown">
						<view class="breakdown-item">
							<view class="breakdown-icon">🏢</view>
							<view class="breakdown-content">
								<text class="breakdown-label">设备费用</text>
								<text class="breakdown-value">{{ formatCurrency(inputFormData.equipmentCost) }}</text>
							</view>
							<view class="breakdown-percent">
								<text
									class="percent-text">{{ ((inputFormData.equipmentCost / totalInvestmentCost) * 100).toFixed(1) }}%</text>
							</view>
						</view>

						<view class="breakdown-item">
							<view class="breakdown-icon">🎨</view>
							<view class="breakdown-content">
								<text class="breakdown-label">装修费用</text>
								<text class="breakdown-value">{{ formatCurrency(inputFormData.renovationCost) }}</text>
							</view>
							<view class="breakdown-percent">
								<text
									class="percent-text">{{ ((inputFormData.renovationCost / totalInvestmentCost) * 100).toFixed(1) }}%</text>
							</view>
						</view>

						<view class="breakdown-item">
							<view class="breakdown-icon">📦</view>
							<view class="breakdown-content">
								<text class="breakdown-label">首批采购</text>
								<text
									class="breakdown-value">{{ formatCurrency(inputFormData.firstPurchaseCost) }}</text>
							</view>
							<view class="breakdown-percent">
								<text
									class="percent-text">{{ ((inputFormData.firstPurchaseCost / totalInvestmentCost) * 100).toFixed(1) }}%</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 关键财务指标卡片 -->
			<view class="result-card">
				<view class="result-header">
					<text class="result-title">📈 关键财务指标</text>
				</view>
				<view class="result-content">
					<view class="result-grid four-column">
						<view class="result-item">
							<text class="result-label">月固定成本</text>
							<text class="result-value">{{ formatCurrency(results.breakEven.totalFixedCost) }}</text>
						</view>

						<view class="result-item">
							<text class="result-label">综合毛利率</text>
							<text class="result-value">{{ results.compositeMargin.toFixed(2) }}%</text>
						</view>

						<view class="result-item">
							<text class="result-label">平均损耗率</text>
							<text class="result-value">{{ results.averageLoss.toFixed(2) }}%</text>
						</view>

						<view class="result-item">
							<text class="result-label">有效毛利率</text>
							<text
								class="result-value highlight-value">{{ results.breakEven.effectiveGrossMargin.toFixed(2) }}%</text>
						</view>
					</view>
				</view>
			</view>

			<!-- ==================== 盈亏信息 ==================== -->

			<!-- 盈亏平衡点分析 -->
			<view class="result-card">
				<view class="result-header">
					<text class="result-title">⚖️ 盈亏平衡点分析</text>
				</view>
				<view class="result-content">
					<view class="result-grid">
						<view class="result-item">
							<text class="result-label">月盈亏平衡销售额</text>
							<text
								class="result-value">{{ formatCurrency(results.breakEven.monthlyBreakEvenSales) }}</text>
							<text class="result-note">达到此销售额即可保本</text>
						</view>

						<view class="result-item">
							<text class="result-label">日平衡销售额</text>
							<text
								class="result-value">{{ formatCurrency(results.breakEven.dailyBreakEvenSales) }}</text>
							<text class="result-note">每天需要达到的最低销售额</text>
						</view>

						<view class="result-item">
							<text class="result-label">日平衡客流量</text>
							<text class="result-value">{{ results.breakEven.dailyBreakEvenCustomers }} 人</text>
							<text class="result-note">按客单价{{ formatCurrency(inputFormData.averagePrice) }}计算</text>
						</view>

						<view class="result-item">
							<text class="result-label">月平衡客流量</text>
							<text
								class="result-value">{{ (results.breakEven.dailyBreakEvenCustomers * inputFormData.businessDays).toLocaleString() }}
								人</text>
							<text class="result-note">整月需要的最低客流</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 经营能力评估卡片 -->
			<view class="result-card assessment-card">
				<view class="result-header">
					<text class="result-title">⭐ 经营能力评估</text>
				</view>
				<view class="assessment-content">
					<view class="assessment-level">
						<text class="level-label">综合评级</text>
						<view class="level-badge" :style="{ background: getBusinessLevelColor() }">
							<text class="level-icon">{{ getBusinessLevelIcon() }}</text>
							<text class="level-text">{{ getBusinessLevel() }}</text>
						</view>
					</view>
					<view class="assessment-details">
						<view class="detail-item">
							<text class="detail-label">盈利能力</text>
							<view class="progress-bar">
								<view class="progress-fill"
									:style="{ width: getProfitAbilityScore() + '%', background: getProfitAbilityColor() }">
								</view>
							</view>
							<text class="detail-value">{{ getProfitAbilityScore() }}分</text>
						</view>
						<view class="detail-item">
							<text class="detail-label">成本控制</text>
							<view class="progress-bar">
								<view class="progress-fill"
									:style="{ width: getCostControlScore() + '%', background: getCostControlColor() }">
								</view>
							</view>
							<text class="detail-value">{{ getCostControlScore() }}分</text>
						</view>
					</view>
				</view>
			</view>

			<!-- ==================== 客流对比 ==================== -->

			<!-- 客流对比分析卡片 -->
			<view class="result-card customer-flow-card">
				<view class="result-header">
					<text class="result-title">👥 客流对比分析</text>
				</view>
				<view class="result-content">
					<!-- 客流达成率可视化 -->
					<view class="flow-achievement-wrapper">
						<view class="achievement-header">
							<text class="achievement-label">客流达成率</text>
							<text class="achievement-value" :style="{ color: getFlowAchievementColor() }">
								{{ customerFlowAnalysis.achievementRate.toFixed(1) }}%
							</text>
						</view>
						<view class="achievement-bar">
							<view class="achievement-fill" :style="{ 
									width: Math.min(customerFlowAnalysis.achievementRate, 100) + '%', 
									background: getFlowAchievementColor() 
								}">
							</view>
						</view>
						<view class="achievement-status" :style="{ color: getFlowAchievementColor() }">
							<text class="status-icon">{{ getFlowStatusIcon() }}</text>
							<text class="status-text">{{ getFlowStatusText() }}</text>
						</view>
					</view>

					<!-- 客流数据对比 -->
					<view class="flow-comparison">
						<view class="flow-item">
							<text class="flow-label">预计日均客流</text>
							<text class="flow-value primary">{{ inputFormData.estimatedCustomers }} 人</text>
						</view>
						<view class="flow-divider">
							<text class="vs-text">VS</text>
						</view>
						<view class="flow-item">
							<text class="flow-label">盈亏平衡客流</text>
							<text class="flow-value">{{ results.breakEven.dailyBreakEvenCustomers }} 人</text>
						</view>
					</view>

					<!-- 客流缺口/盈余 -->
					<view class="flow-gap" :class="{ 'surplus': customerFlowAnalysis.flowGap >= 0 }">
						<text class="gap-label">{{ customerFlowAnalysis.flowGap >= 0 ? '客流盈余' : '客流缺口' }}</text>
						<text class="gap-value">{{ Math.abs(customerFlowAnalysis.flowGap) }} 人/天</text>
						<text class="gap-note">
							{{ customerFlowAnalysis.flowGap >= 0 
								? `每日多出${Math.abs(customerFlowAnalysis.flowGap)}人，有盈利空间` 
								: `每日缺少${Math.abs(customerFlowAnalysis.flowGap)}人，需加强引流` 
							}}
						</text>
					</view>
				</view>
			</view>

			<!-- 预期盈利分析卡片 -->
			<view class="result-card profit-forecast-card" v-if="inputFormData.estimatedCustomers > 0">
				<view class="result-header">
					<text class="result-title">📈 预期盈利分析</text>
				</view>
				<view class="result-content">
					<view class="result-grid">
						<view class="result-item">
							<text class="result-label">预期月销售额</text>
							<text class="result-value">{{ formatCurrency(profitForecast.expectedMonthlySales) }}</text>
							<text class="result-note">预计客流 × 客单价 × 营业天数</text>
						</view>

						<view class="result-item">
							<text class="result-label">预期月毛利</text>
							<text
								class="result-value">{{ formatCurrency(profitForecast.expectedMonthlyGrossProfit) }}</text>
							<text class="result-note">月销售额 × 有效毛利率</text>
						</view>

						<view class="result-item"
							:class="{ 'highlight-success': profitForecast.expectedMonthlyNetProfit > 0, 'highlight-danger': profitForecast.expectedMonthlyNetProfit <= 0 }">
							<text class="result-label">预期月净利润</text>
							<text class="result-value"
								:style="{ color: profitForecast.expectedMonthlyNetProfit > 0 ? '#10b981' : '#ef4444' }">
								{{ formatCurrency(profitForecast.expectedMonthlyNetProfit) }}
							</text>
							<text class="result-note">月毛利 - 月固定成本</text>
						</view>

						<view class="result-item">
							<text class="result-label">预期年净利润</text>
							<text class="result-value"
								:style="{ color: profitForecast.expectedAnnualNetProfit > 0 ? '#10b981' : '#ef4444' }">
								{{ formatCurrency(profitForecast.expectedAnnualNetProfit) }}
							</text>
							<text class="result-note">月净利润 × 12个月</text>
						</view>
					</view>

					<!-- 投资回报预估 -->
					<view class="roi-analysis" v-if="profitForecast.expectedMonthlyNetProfit > 0">
						<view class="roi-item">
							<text class="roi-label">预计回本时间</text>
							<text class="roi-value">{{ formatPaybackPeriod(profitForecast.paybackMonths) }}</text>
						</view>
						<view class="roi-item">
							<text class="roi-label">年投资回报率</text>
							<text class="roi-value">{{ profitForecast.annualROI.toFixed(1) }}%</text>
						</view>
					</view>
				</view>
			</view>

			<!-- ==================== 详细分析 ==================== -->

			<!-- 品类结构分析卡片 -->
			<view class="result-card">
				<view class="result-header">
					<text class="result-title">🥬 品类结构分析</text>
				</view>
				<view class="result-content">
					<view class="category-analysis">
						<view class="category-row" v-for="category in categoryAnalysis" :key="category.name">
							<view class="category-info">
								<text class="category-name">{{ category.name }}</text>
								<text class="category-ratio">占比 {{ category.ratio }}%</text>
							</view>
							<view class="category-metrics">
								<view class="metric">
									<text class="metric-label">毛利率</text>
									<text class="metric-value">{{ category.margin }}%</text>
								</view>
								<view class="metric">
									<text class="metric-label">损耗率</text>
									<text class="metric-value">{{ category.loss }}%</text>
								</view>
								<view class="metric highlight">
									<text class="metric-label">实际毛利</text>
									<text class="metric-value">{{ category.actualMargin.toFixed(2) }}%</text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 成本结构分析卡片 -->
			<view class="result-card">
				<view class="result-header">
					<text class="result-title">💼 成本结构分析</text>
				</view>
				<view class="result-content">
					<view class="cost-structure">
						<view class="cost-row" v-for="cost in costStructure" :key="cost.name">
							<view class="cost-info">
								<text class="cost-name">{{ cost.name }}</text>
								<text class="cost-amount">{{ formatCurrency(cost.amount) }}</text>
							</view>
							<view class="cost-bar-wrapper">
								<view class="cost-bar">
									<view class="cost-bar-fill"
										:style="{ width: cost.percentage + '%', background: cost.color }"></view>
								</view>
								<text class="cost-percentage">{{ cost.percentage.toFixed(1) }}%</text>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- ==================== 经营建议 ==================== -->

			<!-- 综合经营建议区域 -->
			<view class="advice-card enhanced-advice">
				<view class="advice-header">
					<view class="icon-container">💡</view>
					<text class="advice-title">综合经营建议</text>
				</view>
				<view class="advice-content">
					<view class="advice-section" v-for="(section, index) in enhancedBusinessAdvice" :key="index">
						<text class="advice-section-title">{{ section.title }}</text>
						<text class="advice-text" v-for="(advice, idx) in section.items" :key="idx">{{ advice }}</text>
					</view>
				</view>
			</view>

			<!-- 行业提醒 -->
			<view class="industry-tip">
				<text class="tip-content">
					<text class="tip-highlight">🔔 生鲜行业特别提醒：</text>
					请务必考虑商品损耗率对毛利率的影响。损耗会显著降低实际毛利率，特别是蔬菜水果类商品。建议通过优化供应链、改善陈列方式、加强库存管理等手段降低损耗。
				</text>
			</view>

			<!-- 返回按钮，在所有状态下都显示在下方 -->
			<view class="btn-group">
				<button class="btn btn-primary" @click="activeTab = 'input'">返回信息录入</button>
			</view>
		</scroll-view>

		
	</view>
</template>

<script setup lang="ts">
	import { ref, computed } from 'vue';
	import { onLoad } from '@dcloudio/uni-app';
	import NavBar from '@/components/nav-bar.vue';
	import { ProfitPredictionInputData, ProfitPredictionResultData, BreakEvenResult } from '@/types/profit-prediction';
	import { getThemeStyles } from '@/stores/theme';
	import { getDetailAPI } from '@/services/project';
	import { updateTaskAPI } from '@/services/task';
	import { saveProfitPredictionAPI, getProfitPredictionAPI } from '@/services/profit-prediction';
	import { TaskType, TaskStatus } from '@/types/project';
	import { showToast, showLoading, hideLoading, getSafeAreaTop, navigateTo, formatNumber, formatCurrency } from '@/utils/global';
	// 项目ID（从URL参数获取）
	const projectId = ref<number>(0);
	const taskId = ref<number>(0);
	const projectName = ref<string>('');

	// 当前激活的选项卡
	const activeTab = ref<'input' | 'result'>('input');



	// 输入数据（需要保存到后端）
	const inputFormData = ref<ProfitPredictionInputData>({
		equipmentCost: 0,
		renovationCost: 0,
		firstPurchaseCost: 0,
		rentAndPropertyCost: 0,
		staffSalaryAndInsurance: 0,
		utilitiesAndMisc: 0,
		managementAndMarketing: 0,
		loanInterest: 0,
		otherCosts: 0,
		vegetableRatio: 0,
		vegetableMargin: 0,
		vegetableLoss: 0,
		meatRatio: 0,
		meatMargin: 0,
		meatLoss: 0,
		dryRatio: 0,
		dryMargin: 0,
		dryLoss: 0,
		dailyRatio: 0,
		dailyMargin: 0,
		dailyLoss: 0,
		averagePrice: 0,
		businessDays: 0,
		estimatedCustomers: 0,
	});

	// 统一的计算结果对象
	const results = ref<ProfitPredictionResultData>({
		totalRatio: 0,
		compositeMargin: 0,
		averageLoss: 0,
		breakEven: {
			totalFixedCost: 0,
			monthlyBreakEvenSales: 0,
			dailyBreakEvenSales: 0,
			dailyBreakEvenCustomers: 0,
			effectiveGrossMargin: 0
		},
		businessAdvice: []
	});

	// 验证错误状态
	const validationErrors = ref({
		ratio: false,      // 销售占比错误
		ratioMessage: '',  // 销售占比错误信息
	});

	// ==================== Computed自动计算（简单相加） ====================

	/**
	 * 自动计算总投资成本
	 * 公式：设备费用 + 装修费用 + 首批采购成本
	 */
	const totalInvestmentCost = computed(() => {
		return Number(inputFormData.value.equipmentCost || 0)
			+ Number(inputFormData.value.renovationCost || 0)
			+ Number(inputFormData.value.firstPurchaseCost || 0);
	});

	/**
	 * 自动计算月运营成本总额
	 * 公式：房租物业费 + 员工工资 + 水电杂费 + 管理营销费 + 贷款利息 + 其他费用
	 */
	const totalMonthlyOperatingCost = computed(() => {
		return Number(inputFormData.value.rentAndPropertyCost || 0) +
			Number(inputFormData.value.staffSalaryAndInsurance || 0) +
			Number(inputFormData.value.utilitiesAndMisc || 0) +
			Number(inputFormData.value.managementAndMarketing || 0) +
			Number(inputFormData.value.loanInterest || 0) +
			Number(inputFormData.value.otherCosts || 0);
	});

	/**
	 * 实时计算综合毛利率（用于输入区域显示）
	 * 公式：考虑损耗后的加权平均毛利率
	 */
	const realtimeCompositeMargin = computed(() => {
		return calculateCompositeMargin();
	});

	/**
	 * 实时计算平均损耗率（用于输入区域显示）
	 * 公式：各品类损耗率的加权平均
	 */
	const realtimeAverageLoss = computed(() => {
		return calculateAverageLoss();
	});

	/**
	 * 计算总销售占比
	 * @returns 各类别销售占比之和
	 */
	const calculateTotalRatio = () : number => {
		return (Number(inputFormData.value.vegetableRatio || 0) +
			Number(inputFormData.value.meatRatio || 0) +
			Number(inputFormData.value.dryRatio || 0) +
			Number(inputFormData.value.dailyRatio || 0))
	};

	/**
	 * 计算考虑损耗后的实际毛利率
	 * @param margin 毛利率
	 * @param loss 损耗率
	 * @returns 实际毛利率
	 */
	const calculateActualMargin = (margin : number, loss : number) : number => {
		return margin * (1 - loss / 100);
	};

	/**
	 * 计算综合毛利率（考虑损耗）
	 * @returns 综合毛利率
	 */
	const calculateCompositeMargin = () : number => {
		const totalRatio = calculateTotalRatio();
		if (totalRatio <= 0) return 0;

		// 计算各类别考虑损耗后的实际毛利率，确保使用默认值
		const vegActualMargin = calculateActualMargin(inputFormData.value.vegetableMargin || 0, inputFormData.value.vegetableLoss || 0);
		const meatActualMargin = calculateActualMargin(inputFormData.value.meatMargin || 0, inputFormData.value.meatLoss || 0);
		const dryActualMargin = calculateActualMargin(inputFormData.value.dryMargin || 0, inputFormData.value.dryLoss || 0);
		const dailyActualMargin = calculateActualMargin(inputFormData.value.dailyMargin || 0, inputFormData.value.dailyLoss || 0);

		// 计算加权平均的综合毛利率
		return (
			vegActualMargin * (inputFormData.value.vegetableRatio || 0) +
			meatActualMargin * (inputFormData.value.meatRatio || 0) +
			dryActualMargin * (inputFormData.value.dryRatio || 0) +
			dailyActualMargin * (inputFormData.value.dailyRatio || 0)
		) / totalRatio;
	};

	/**
	 * 计算平均损耗率
	 * @returns 平均损耗率
	 */
	const calculateAverageLoss = () : number => {
		const totalRatio = calculateTotalRatio();
		if (totalRatio <= 0) return 0;

		return (
			((inputFormData.value.vegetableLoss || 0) * (inputFormData.value.vegetableRatio || 0)) +
			((inputFormData.value.meatLoss || 0) * (inputFormData.value.meatRatio || 0)) +
			((inputFormData.value.dryLoss || 0) * (inputFormData.value.dryRatio || 0)) +
			((inputFormData.value.dailyLoss || 0) * (inputFormData.value.dailyRatio || 0))
		) / totalRatio;
	};

	/**
	 * 计算月固定成本总额
	 * @returns 月固定成本总额
	 */
	const calculateTotalFixedCost = () : number => {
		// 确保每个字段都有值，避免NaN结果
		return (inputFormData.value.rentAndPropertyCost || 0) +
			(inputFormData.value.staffSalaryAndInsurance || 0) +
			(inputFormData.value.utilitiesAndMisc || 0) +
			(inputFormData.value.managementAndMarketing || 0) +
			(inputFormData.value.loanInterest || 0) +
			(inputFormData.value.otherCosts || 0);
	};


	/**
	 * 计算月盈亏平衡销售额
	 * @param totalFixedCost 月固定成本总额
	 * @param compositeMargin 综合毛利率
	 * @param averageLoss 平均损耗率
	 * @returns 月盈亏平衡销售额
	 */
	const calculateMonthlyBreakEvenSales = (totalFixedCost : number, compositeMargin : number, averageLoss : number) : number => {
		if (compositeMargin <= averageLoss) return 0;
		return Math.round(totalFixedCost / (compositeMargin / 100 - averageLoss / 100));
	};

	/**
	 * 计算日平衡客流量
	 * @param monthlyBreakEvenSales 月盈亏平衡销售额
	 * @param averagePrice 平均客单价
	 * @param businessDays 每月营业天数
	 * @returns 日平衡客流量
	 */
	const calculateDailyBreakEvenCustomers = (monthlyBreakEvenSales : number, averagePrice : number, businessDays : number) : number => {
		// 确保参数有效
		monthlyBreakEvenSales = monthlyBreakEvenSales || 0;
		averagePrice = averagePrice || 0;
		businessDays = businessDays || 0;

		if (averagePrice <= 0 || businessDays <= 0) return 0;
		const monthlyTransactions = monthlyBreakEvenSales / averagePrice;
		return Math.round(monthlyTransactions / businessDays);
	};

	/**
	 * 计算盈亏平衡结果
	 * @returns 盈亏平衡分析结果
	 */
	const calculateBreakEvenResult = () : BreakEvenResult => {
		// 计算月固定成本总额
		const totalFixedCost = calculateTotalFixedCost();

		// 计算综合毛利率
		const compositeMargin = calculateCompositeMargin();

		// 计算平均损耗率
		const averageLoss = calculateAverageLoss();

		// 计算月盈亏平衡销售额
		const monthlyBreakEvenSales = calculateMonthlyBreakEvenSales(totalFixedCost, compositeMargin, averageLoss);

		// 计算日平衡客流量
		const dailyBreakEvenCustomers = calculateDailyBreakEvenCustomers(
			monthlyBreakEvenSales,
			inputFormData.value.averagePrice,
			inputFormData.value.businessDays
		);

		// 计算日盈亏平衡销售额=月盈亏平衡销售额÷每月营业天数
		const dailyBreakEvenSales = Math.round(monthlyBreakEvenSales / (inputFormData.value.businessDays || 1));

		return {
			totalFixedCost,
			monthlyBreakEvenSales,
			dailyBreakEvenSales,
			dailyBreakEvenCustomers,
			effectiveGrossMargin: compositeMargin - averageLoss
		};
	};

	// ==================== 数据验证相关 ====================

	/**
	 * 通用的百分比总和验证函数
	 * @param values 需要验证的数值数组
	 * @param fieldName 字段名称（用于错误提示）
	 * @returns 是否验证通过
	 */
	const validatePercentageSum = (values : number[], fieldName : string) : boolean => {
		// 使用reduce累加计算总和（acc: 累加值, cur: 当前值）
		const sum = values.reduce((acc, cur) => acc + Number(cur || 0), 0);

		if (sum !== 100) {
			// 设置错误状态，不弹出Toast
			validationErrors.value.ratio = true;
			validationErrors.value.ratioMessage = `${fieldName}总和必须等于100%（当前为${sum.toFixed(1)}%）`;
			return false;
		}

		// 验证通过，清除错误状态
		validationErrors.value.ratio = false;
		validationErrors.value.ratioMessage = '';
		return true;
	};

	/**
	 * 验证销售占比总和
	 * 确保蔬菜、肉类、干货、日用品的销售占比总和为100%
	 */
	const validatetRatio = () : boolean => {
		const values = [
			inputFormData.value.vegetableRatio,
			inputFormData.value.meatRatio,
			inputFormData.value.dryRatio,
			inputFormData.value.dailyRatio
		];

		return validatePercentageSum(values, '销售占比');
	};

	/**
	 * 验证毛利率（仅检查范围，不要求总和为100%）
	 * 确保各品类毛利率在合理范围内（0-100%）
	 */
	const validateMargin = () : boolean => {
		// 毛利率不需要总和为100%，只需确保每个值在0-100之间
		return true;
	};

	/**
	 * 验证损耗率（仅检查范围，不要求总和为100%）
	 * 确保各品类损耗率在合理范围内（0-100%）
	 */
	const validateLoss = () : boolean => {
		// 损耗率不需要总和为100%，只需确保每个值在0-100之间
		return true;
	};


	// ==================== 综合计算相关 ====================

	/**
	 * 更新经营建议
	 * 根据计算出的综合毛利率和平均损耗率，提供针对性的经营建议
	 */
	const updateBusinessAdvice = () : string[] => {
		const advice : string[] = [];
		const compositeMargin = results.value.compositeMargin;
		const averageLoss = results.value.averageLoss;

		// 检查综合毛利率
		if (compositeMargin < 15) {
			advice.push('当前综合毛利率偏低，建议优化商品结构或控制采购成本。');
		} else if (compositeMargin > 25) {
			advice.push('综合毛利率良好，可适当考虑促销活动提升销售额。');
		}

		// 检查损耗率
		if (averageLoss > 8) {
			advice.push('损耗率较高，尤其是蔬菜水果类，建议加强库存管理和优化陈列方式。');
		}

		// 提供通用建议
		advice.push('建议定期分析销售数据，调整商品结构以提高盈利能力。');
		advice.push('关注客流量与客单价的平衡，通过提升服务质量和优化商品组合来提高销售额。');

		return advice;
	};

	// ==================== 结果展示相关辅助方法 ====================

	/**
	 * 客流对比分析
	 */
	const customerFlowAnalysis = computed(() => {
		const estimated = inputFormData.value.estimatedCustomers || 0;
		const breakEven = results.value.breakEven.dailyBreakEvenCustomers || 0;

		// 客流缺口/盈余
		const flowGap = estimated - breakEven;

		// 客流达成率
		const achievementRate = breakEven > 0 ? (estimated / breakEven) * 100 : 0;

		return {
			flowGap,
			achievementRate
		};
	});

	/**
	 * 预期盈利分析
	 */
	const profitForecast = computed(() => {
		const estimatedCustomers = inputFormData.value.estimatedCustomers || 0;
		const averagePrice = inputFormData.value.averagePrice || 0;
		const businessDays = inputFormData.value.businessDays || 0;
		const effectiveMargin = results.value.breakEven.effectiveGrossMargin || 0;
		const monthlyFixedCost = results.value.breakEven.totalFixedCost || 0;
		const totalInvestment = totalInvestmentCost.value;

		// 预期月销售额 = 预计日均客流 × 客单价 × 营业天数
		const expectedMonthlySales = estimatedCustomers * averagePrice * businessDays;

		// 预期月毛利 = 月销售额 × 有效毛利率
		const expectedMonthlyGrossProfit = expectedMonthlySales * (effectiveMargin / 100);

		// 预期月净利润 = 月毛利 - 月固定成本
		const expectedMonthlyNetProfit = expectedMonthlyGrossProfit - monthlyFixedCost;

		// 预期年净利润
		const expectedAnnualNetProfit = expectedMonthlyNetProfit * 12;

		// 预计回本时间（月）
		const paybackMonths = expectedMonthlyNetProfit > 0 ? totalInvestment / expectedMonthlyNetProfit : Infinity;

		// 年投资回报率 = 年净利润 / 总投资 × 100%
		const annualROI = totalInvestment > 0 ? (expectedAnnualNetProfit / totalInvestment) * 100 : 0;

		return {
			expectedMonthlySales,
			expectedMonthlyGrossProfit,
			expectedMonthlyNetProfit,
			expectedAnnualNetProfit,
			paybackMonths,
			annualROI
		};
	});

	/**
	 * 获取客流达成率颜色
	 */
	const getFlowAchievementColor = () : string => {
		const rate = customerFlowAnalysis.value.achievementRate;
		if (rate >= 200) return '#10b981'; // 绿色 - 客流充足
		if (rate >= 150) return '#34d399'; // 浅绿 - 客流良好
		if (rate >= 100) return '#fbbf24'; // 黄色 - 勉强达标
		if (rate >= 80) return '#f59e0b';  // 橙色 - 存在风险
		return '#ef4444'; // 红色 - 严重不足
	};

	/**
	 * 获取客流状态图标
	 */
	const getFlowStatusIcon = () : string => {
		const rate = customerFlowAnalysis.value.achievementRate;
		if (rate >= 200) return '🎉';
		if (rate >= 150) return '✅';
		if (rate >= 100) return '⚠️';
		if (rate >= 80) return '⚡';
		return '❌';
	};

	/**
	 * 获取客流状态文本
	 */
	const getFlowStatusText = () : string => {
		const rate = customerFlowAnalysis.value.achievementRate;
		if (rate >= 200) return '客流充足，盈利可观';
		if (rate >= 150) return '客流良好，稳健盈利';
		if (rate >= 100) return '刚好达标，需持续优化';
		if (rate >= 80) return '客流不足，存在亏损风险';
		return '客流严重不足，需紧急调整';
	};

	/**
	 * 格式化回本时间
	 */
	const formatPaybackPeriod = (months : number) : string => {
		if (months === Infinity || months <= 0 || isNaN(months)) {
			return '无法回本';
		}
		if (months < 1) {
			return '不到1个月';
		}
		if (months < 12) {
			return `${months.toFixed(1)}个月`;
		}
		const years = (months / 12).toFixed(1);
		return `${years}年`;
	};

	/**
	 * 获取经营能力等级
	 */
	const getBusinessLevel = () : string => {
		const score = getBusinessScore();
		if (score >= 85) return '优秀';
		if (score >= 70) return '良好';
		if (score >= 55) return '一般';
		if (score >= 40) return '较差';
		return '困难';
	};

	/**
	 * 获取经营能力等级图标
	 */
	const getBusinessLevelIcon = () : string => {
		const score = getBusinessScore();
		if (score >= 85) return '🟢';
		if (score >= 70) return '🟡';
		if (score >= 55) return '🟠';
		if (score >= 40) return '🔴';
		return '⚫';
	};

	/**
	 * 获取经营能力等级颜色
	 */
	const getBusinessLevelColor = () : string => {
		const score = getBusinessScore();
		if (score >= 85) return 'linear-gradient(135deg, #10b981 0%, #34d399 100%)';
		if (score >= 70) return 'linear-gradient(135deg, #fbbf24 0%, #fcd34d 100%)';
		if (score >= 55) return 'linear-gradient(135deg, #f59e0b 0%, #fbbf24 100%)';
		if (score >= 40) return 'linear-gradient(135deg, #ef4444 0%, #f87171 100%)';
		return 'linear-gradient(135deg, #dc2626 0%, #ef4444 100%)';
	};

	/**
	 * 计算综合经营分数
	 */
	const getBusinessScore = () : number => {
		const profitScore = getProfitAbilityScore();
		const costScore = getCostControlScore();
		return Math.round((profitScore + costScore) / 2);
	};

	/**
	 * 获取盈利能力分数（0-100）
	 */
	const getProfitAbilityScore = () : number => {
		const margin = results.value.compositeMargin;
		const loss = results.value.averageLoss;
		const effectiveMargin = margin - loss;

		// 基于有效毛利率评分
		let score = 0;
		if (effectiveMargin >= 25) score = 100;
		else if (effectiveMargin >= 20) score = 85;
		else if (effectiveMargin >= 15) score = 70;
		else if (effectiveMargin >= 10) score = 55;
		else if (effectiveMargin >= 5) score = 40;
		else score = 20;

		return score;
	};

	/**
	 * 获取盈利能力颜色
	 */
	const getProfitAbilityColor = () : string => {
		const score = getProfitAbilityScore();
		if (score >= 85) return '#10b981';
		if (score >= 70) return '#fbbf24';
		if (score >= 55) return '#f59e0b';
		return '#ef4444';
	};

	/**
	 * 获取成本控制分数（0-100）
	 * 基于月固定成本占总投资的比例评分
	 */
	const getCostControlScore = () : number => {
		const totalCost = results.value.breakEven.totalFixedCost;
		const totalInvestment = totalInvestmentCost.value;

		if (totalInvestment <= 0) return 50;

		// 计算月成本占总投资的比例
		const costRatio = (totalCost / totalInvestment) * 100;

		// 基于成本比例评分
		// 月成本越低（相对于投资），分数越高
		let score = 0;
		if (costRatio < 5) {
			score = 100; // 月成本低于投资的5%，成本控制优秀
		} else if (costRatio < 10) {
			score = 85;  // 月成本5-10%，成本控制良好
		} else if (costRatio < 15) {
			score = 70;  // 月成本10-15%，成本控制一般
		} else if (costRatio < 20) {
			score = 55;  // 月成本15-20%，成本控制较差
		} else {
			score = 40;  // 月成本超过20%，成本压力大
		}

		return score;
	};

	/**
	 * 获取成本控制颜色
	 */
	const getCostControlColor = () : string => {
		const score = getCostControlScore();
		if (score >= 85) return '#10b981';
		if (score >= 70) return '#fbbf24';
		if (score >= 55) return '#f59e0b';
		return '#ef4444';
	};

	/**
	 * 品类分析数据
	 */
	const categoryAnalysis = computed(() => {
		return [
			{
				name: '蔬菜水果',
				ratio: inputFormData.value.vegetableRatio || 0,
				margin: inputFormData.value.vegetableMargin || 0,
				loss: inputFormData.value.vegetableLoss || 0,
				actualMargin: calculateActualMargin(inputFormData.value.vegetableMargin || 0, inputFormData.value.vegetableLoss || 0)
			},
			{
				name: '肉类水产',
				ratio: inputFormData.value.meatRatio || 0,
				margin: inputFormData.value.meatMargin || 0,
				loss: inputFormData.value.meatLoss || 0,
				actualMargin: calculateActualMargin(inputFormData.value.meatMargin || 0, inputFormData.value.meatLoss || 0)
			},
			{
				name: '干货粮油',
				ratio: inputFormData.value.dryRatio || 0,
				margin: inputFormData.value.dryMargin || 0,
				loss: inputFormData.value.dryLoss || 0,
				actualMargin: calculateActualMargin(inputFormData.value.dryMargin || 0, inputFormData.value.dryLoss || 0)
			},
			{
				name: '日用品',
				ratio: inputFormData.value.dailyRatio || 0,
				margin: inputFormData.value.dailyMargin || 0,
				loss: inputFormData.value.dailyLoss || 0,
				actualMargin: calculateActualMargin(inputFormData.value.dailyMargin || 0, inputFormData.value.dailyLoss || 0)
			}
		].sort((a, b) => b.actualMargin - a.actualMargin); // 按实际毛利率降序排列
	});

	/**
	 * 成本结构数据
	 */
	const costStructure = computed(() => {
		const total = results.value.breakEven.totalFixedCost;
		if (total <= 0) return [];

		const costs = [
			{ name: '房租物业', amount: inputFormData.value.rentAndPropertyCost || 0, color: '#3b82f6' },
			{ name: '员工工资', amount: inputFormData.value.staffSalaryAndInsurance || 0, color: '#10b981' },
			{ name: '水电杂费', amount: inputFormData.value.utilitiesAndMisc || 0, color: '#f59e0b' },
			{ name: '管理营销', amount: inputFormData.value.managementAndMarketing || 0, color: '#8b5cf6' },
			{ name: '贷款利息', amount: inputFormData.value.loanInterest || 0, color: '#ef4444' },
			{ name: '其他费用', amount: inputFormData.value.otherCosts || 0, color: '#64748b' }
		];

		return costs.map(cost => ({
			...cost,
			percentage: (cost.amount / total) * 100
		})).sort((a, b) => b.amount - a.amount); // 按金额降序排列
	});

	/**
	 * 增强的经营建议（分类）
	 */
	const enhancedBusinessAdvice = computed(() => {
		const advice : Array<{ title : string; items : string[] }> = [];
		const margin = results.value.compositeMargin;
		const loss = results.value.averageLoss;
		const effectiveMargin = margin - loss;
		const totalCost = results.value.breakEven.totalFixedCost;
		const totalInvestment = totalInvestmentCost.value;

		// 1. 盈利能力建议
		const profitAdvice = {
			title: '💰 盈利能力提升',
			items: [] as string[]
		};

		if (effectiveMargin < 15) {
			profitAdvice.items.push('当前有效毛利率偏低，建议增加高毛利品类（如日用品、干货粮油）的占比');
			profitAdvice.items.push('与供应商洽谈更优惠的采购价格，或寻找质量相当但价格更低的替代供应商');
		} else if (effectiveMargin >= 20) {
			profitAdvice.items.push('毛利率控制良好，建议保持现有品类结构，同时关注销售额提升');
		}

		advice.push(profitAdvice);

		// 2. 成本控制建议
		const costAdvice = {
			title: '💼 成本控制优化',
			items: [] as string[]
		};

		// 分析成本结构
		const costData = costStructure.value;
		if (costData.length > 0) {
			const maxCost = costData[0];
			if (maxCost.percentage > 40) {
				costAdvice.items.push(`${maxCost.name}占比过高(${maxCost.percentage.toFixed(1)}%)，建议重点优化此项成本`);
			}
		}

		// 分析月成本占投资比例
		if (totalInvestment > 0) {
			const costRatio = (totalCost / totalInvestment) * 100;
			if (costRatio > 15) {
				costAdvice.items.push(`月运营成本占总投资${costRatio.toFixed(1)}%，建议严格控制各项运营成本，提高资金使用效率`);
			}
		}

		costAdvice.items.push('定期审查各项费用支出，及时调整不合理的成本项目');

		advice.push(costAdvice);

		// 3. 损耗管理建议
		const lossAdvice = {
			title: '📦 损耗管理改善',
			items: [] as string[]
		};

		if (loss > 8) {
			lossAdvice.items.push('当前损耗率较高，建议加强库存周转管理，采用"少量多次"的采购策略');
			lossAdvice.items.push('优化商品陈列和存储条件，特别是蔬菜水果类的冷链管理');
		}

		// 分析哪个品类损耗最高
		const categories = categoryAnalysis.value;
		const maxLossCategory = categories.reduce((prev, curr) => (curr.loss > prev.loss ? curr : prev));
		if (maxLossCategory.loss > 10) {
			lossAdvice.items.push(`${maxLossCategory.name}损耗率高达${maxLossCategory.loss}%，建议重点关注该品类的损耗控制`);
		}

		advice.push(lossAdvice);

		// 4. 品类结构建议
		const categoryAdviceSection = {
			title: '🥬 品类结构调整',
			items: [] as string[]
		};

		const bestCategory = categories[0]; // 实际毛利率最高的品类
		const worstCategory = categories[categories.length - 1]; // 实际毛利率最低的品类

		categoryAdviceSection.items.push(`${bestCategory.name}的实际毛利率最高(${bestCategory.actualMargin.toFixed(2)}%)，可适当增加该品类占比`);

		if (worstCategory.actualMargin < 10) {
			categoryAdviceSection.items.push(`${worstCategory.name}的实际毛利率较低(${worstCategory.actualMargin.toFixed(2)}%)，建议优化商品结构或提高售价`);
		}

		advice.push(categoryAdviceSection);

		// 5. 经营策略建议
		const strategyAdvice = {
			title: '🎯 经营策略建议',
			items: [] as string[]
		};

		const dailyCustomers = results.value.breakEven.dailyBreakEvenCustomers;
		const avgPrice = inputFormData.value.averagePrice;
		const estimatedCustomers = inputFormData.value.estimatedCustomers || 0;

		// 基于客流达成率给出建议
		if (estimatedCustomers > 0) {
			const flowGap = estimatedCustomers - dailyCustomers;
			const achievementRate = (estimatedCustomers / dailyCustomers) * 100;

			if (achievementRate >= 150) {
				strategyAdvice.items.push(`当前预计客流${estimatedCustomers}人，超出盈亏平衡${flowGap}人，建议重点优化客单价和复购率`);
				strategyAdvice.items.push('客流充足时，可适当开展促销活动提升销售额，同时加强会员体系建设');
			} else if (achievementRate >= 100) {
				strategyAdvice.items.push(`当前预计客流${estimatedCustomers}人，刚好达到盈亏平衡，建议持续保持客流稳定并寻求突破`);
				strategyAdvice.items.push('建议通过社区营销、口碑传播等低成本方式逐步提升客流');
			} else {
				strategyAdvice.items.push(`⚠️ 当前预计客流${estimatedCustomers}人，距离盈亏平衡还差${Math.abs(flowGap)}人，需重点加强引流`);
				strategyAdvice.items.push('建议加大营销投入，开展地推活动、线上推广、异业合作等多渠道引流');
				strategyAdvice.items.push('考虑优化选址或调整经营策略，确保客流达到最低要求');
			}
		} else {
			strategyAdvice.items.push(`每日至少需要${dailyCustomers}名顾客才能达到盈亏平衡，建议制定精准的客流引流方案`);
		}

		if (avgPrice < 40) {
			strategyAdvice.items.push(`当前客单价${formatCurrency(avgPrice)}偏低，建议通过关联销售、促销套餐等方式提升客单价`);
		}

		strategyAdvice.items.push('建立会员体系，提高客户复购率和忠诚度');
		strategyAdvice.items.push('关注周边竞争对手动态，及时调整价格和促销策略');

		advice.push(strategyAdvice);

		return advice.filter(section => section.items.length > 0);
	});

	/**
	 * 执行所有计算
	 * 更新所有计算结果到统一的results对象中
	 * @returns 是否计算成功
	 */
	const performAllCalculations = () : boolean => {
		// 验证数据
		if (!validatetRatio()) return false;
		if (!validateMargin()) return false;
		if (!validateLoss()) return false;

		// 计算基础数据
		results.value.totalRatio = calculateTotalRatio();
		results.value.compositeMargin = calculateCompositeMargin();
		results.value.averageLoss = calculateAverageLoss();

		// 计算盈亏平衡点
		results.value.breakEven = calculateBreakEvenResult();

		// 生成经营建议
		results.value.businessAdvice = updateBusinessAdvice();

		console.log('performAllCalculations results.value', results.value);
		return true;
	};

	// ==================== 用户操作相关 ====================

	/**
	 * 处理销售占比输入，实时验证
	 */
	const handleRatioInput = () => {
		// 延迟验证，避免用户输入时频繁验证
		setTimeout(() => {
			validatetRatio();
		}, 300);
	};

	/**
	 * 重置数据
	 * 清空所有表单数据和计算结果，恢复到初始状态
	 */
	const handleReset = () : void => {
		// 清空表单数据
		inputFormData.value = {} as ProfitPredictionInputData;

		// 清空计算结果
		results.value = {
			totalRatio: 0,
			compositeMargin: 0,
			averageLoss: 0,
			breakEven: {
				totalFixedCost: 0,
				monthlyBreakEvenSales: 0,
				dailyBreakEvenSales: 0,
				dailyBreakEvenCustomers: 0,
				effectiveGrossMargin: 0
			},
			businessAdvice: []
		};

		// 清空验证错误
		validationErrors.value.ratio = false;
		validationErrors.value.ratioMessage = '';

		showToast('已清空所有数据', 'success');
	};

	/**
	 * 显示经营状况选择器
	 * 用户可以选择不同的经营状况，生成对应的模拟数据
	 */
	const fillWithDemoData = () : void => {
		uni.showActionSheet({
			itemList: [
				'🟢 优秀 - 高毛利低成本（快速盈利）',
				'🟡 良好 - 稳健经营（正常盈利）',
				'🟠 一般 - 收支平衡（盈亏边缘）',
				'🔴 较差 - 成本压力大（较难盈利）',
				'⚫ 困难 - 高成本低毛利（盈利困难）'
			],
			success: (res) => {
				if (!res.cancel) {
					generateDemoDataByLevel(res.tapIndex);
				}
			}
		});
	};

	/**
	 * 根据经营状况等级生成对应的模拟数据
	 * @param levelIndex 经营状况等级索引 (0=优秀, 1=良好, 2=一般, 3=较差, 4=困难)
	 * 
	 * 评分标准：
	 * - 综合评分 = (盈利能力评分 + 成本控制评分) / 2
	 * - 优秀: >= 85, 良好: >= 70, 一般: >= 55, 较差: >= 40, 困难: < 40
	 * 
	 * 盈利能力评分（基于有效毛利率 = 综合毛利率 - 平均损耗率）：
	 * - >= 25%: 100分, >= 20%: 85分, >= 15%: 70分, >= 10%: 55分, >= 5%: 40分, < 5%: 20分
	 * 
	 * 成本控制评分（基于月成本占总投资比例）：
	 * - < 5%: 100分, < 10%: 85分, < 15%: 70分, < 20%: 55分, >= 20%: 40分
	 */
	const generateDemoDataByLevel = (levelIndex : number) : void => {
		// 定义不同经营状况的数据配置
		const levelDataConfigs = [
			// 0 - 优秀：有效毛利率 >= 25%, 成本占比 < 5% => 盈利100分 + 成本100分 = 综合100分 ✅
			// 综合毛利率约30.1%, 平均损耗率约3.8%, 有效毛利率26.3%
			// 总投资800k, 月成本8k, 成本占比1% 
			{
				equipmentCost: 300000,
				renovationCost: 400000,
				firstPurchaseCost: 100000,
				rentAndPropertyCost: 3000,
				staffSalaryAndInsurance: 2000,
				utilitiesAndMisc: 1000,
				managementAndMarketing: 1000,
				loanInterest: 500,
				otherCosts: 500,
				vegetableRatio: 35,
				vegetableMargin: 30,
				vegetableLoss: 5,
				meatRatio: 30,
				meatMargin: 25,
				meatLoss: 3,
				dryRatio: 20,
				dryMargin: 35,
				dryLoss: 1,
				dailyRatio: 15,
				dailyMargin: 40,
				dailyLoss: 1,
				averagePrice: 55,
				businessDays: 30,
				estimatedCustomers: 60  // 实际平衡客流约24，预计60是2.5倍
			},
			// 1 - 良好：有效毛利率 >= 15%, 成本占比 < 15% => 盈利70分 + 成本70分 = 综合70分 ✅
			// 综合毛利率约21.2%, 平均损耗率约5.7%, 有效毛利率15.5%
			// 总投资500k, 月成本58k, 成本占比11.6%
			{
				equipmentCost: 200000,
				renovationCost: 250000,
				firstPurchaseCost: 50000,
				rentAndPropertyCost: 15000,
				staffSalaryAndInsurance: 25000,
				utilitiesAndMisc: 5000,
				managementAndMarketing: 8000,
				loanInterest: 3000,
				otherCosts: 2000,
				vegetableRatio: 40,
				vegetableMargin: 25,
				vegetableLoss: 8,
				meatRatio: 30,
				meatMargin: 20,
				meatLoss: 5,
				dryRatio: 15,
				dryMargin: 30,
				dryLoss: 2,
				dailyRatio: 15,
				dailyMargin: 35,
				dailyLoss: 1,
				averagePrice: 45,
				businessDays: 30,
				estimatedCustomers: 480  // 实际平衡客流约285，预计480是1.7倍
			},
			// 2 - 一般：有效毛利率 >= 10%, 成本占比 < 20% => 盈利55分 + 成本55分 = 综合55分 ✅
			// 综合毛利率约16.5%, 平均损耗率约6.5%, 有效毛利率10%
			// 总投资390k, 月成本74k, 成本占比19%
			{
				equipmentCost: 150000,
				renovationCost: 180000,
				firstPurchaseCost: 60000,
				rentAndPropertyCost: 20000,
				staffSalaryAndInsurance: 30000,
				utilitiesAndMisc: 6000,
				managementAndMarketing: 10000,
				loanInterest: 5000,
				otherCosts: 3000,
				vegetableRatio: 45,
				vegetableMargin: 20,
				vegetableLoss: 10,
				meatRatio: 30,
				meatMargin: 18,
				meatLoss: 6,
				dryRatio: 15,
				dryMargin: 25,
				dryLoss: 3,
				dailyRatio: 10,
				dailyMargin: 30,
				dailyLoss: 2,
				averagePrice: 38,
				businessDays: 30,
				estimatedCustomers: 750  // 实际平衡客流约680，预计750是1.1倍
			},
			// 3 - 较差：有效毛利率 >= 5%, 成本占比 >= 20% => 盈利40分 + 成本40分 = 综合40分 ✅
			// 综合毛利率约13.2%, 平均损耗率约8.2%, 有效毛利率5%
			// 总投资370k, 月成本90k, 成本占比24.3%
			{
				equipmentCost: 120000,
				renovationCost: 180000,
				firstPurchaseCost: 70000,
				rentAndPropertyCost: 25000,
				staffSalaryAndInsurance: 35000,
				utilitiesAndMisc: 8000,
				managementAndMarketing: 12000,
				loanInterest: 6000,
				otherCosts: 4000,
				vegetableRatio: 50,
				vegetableMargin: 18,
				vegetableLoss: 12,
				meatRatio: 28,
				meatMargin: 15,
				meatLoss: 8,
				dryRatio: 12,
				dryMargin: 22,
				dryLoss: 4,
				dailyRatio: 10,
				dailyMargin: 28,
				dailyLoss: 2,
				averagePrice: 32,
				businessDays: 30,
				estimatedCustomers: 900  // 实际平衡客流约1060，预计900是0.85倍
			},
			// 4 - 困难：有效毛利率 < 5%, 成本占比 >= 20% => 盈利20分 + 成本40分 = 综合30分 ✅
			// 综合毛利率约11.4%, 平均损耗率约10.7%, 有效毛利率0.7%
			// 总投资450k, 月成本108k, 成本占比24%
			{
				equipmentCost: 150000,
				renovationCost: 220000,
				firstPurchaseCost: 80000,
				rentAndPropertyCost: 30000,
				staffSalaryAndInsurance: 40000,
				utilitiesAndMisc: 10000,
				managementAndMarketing: 15000,
				loanInterest: 8000,
				otherCosts: 5000,
				vegetableRatio: 55,
				vegetableMargin: 15,
				vegetableLoss: 15,
				meatRatio: 25,
				meatMargin: 12,
				meatLoss: 10,
				dryRatio: 10,
				dryMargin: 20,
				dryLoss: 5,
				dailyRatio: 10,
				dailyMargin: 25,
				dailyLoss: 3,
				averagePrice: 28,
				businessDays: 30,
				estimatedCustomers: 900  // 实际平衡客流约1800，预计900是0.5倍
			}
		];

		// 获取选中等级的数据配置
		const config = levelDataConfigs[levelIndex];

		// 填充数据
		inputFormData.value = { ...config };

		// 清空验证错误
		validationErrors.value.ratio = false;
		validationErrors.value.ratioMessage = '';

		// 触发计算，更新结果
		performAllCalculations();

		// 显示成功提示
		const levels = ['优秀', '良好', '一般', '较差', '困难'];
		showToast(`已填充${levels[levelIndex]}经营状况模拟数据`, 'success');
	};

	/**
	 * 分析结果并保存数据
	 * 点击"分析结果"按钮时调用
	 * 
	 * 执行流程：
	 * 1. 执行所有计算
	 * 2. 保存数据到后端
	 * 3. 更新任务状态为已完成
	 * 4. 切换到结果展示选项卡
	 */
	const handleAnalyzeAndSave = async () : Promise<void> => {
		// 执行所有计算
		const calculationSuccess = performAllCalculations();

		// 如果计算失败（验证不通过），不继续执行
		if (!calculationSuccess) {
			return;
		}

		try {
			showLoading('保存中...');

			// 保存盈利预测数据
			await saveProfitPredictionAPI({
				projectId: projectId.value,
				taskId: taskId.value,
				...inputFormData.value
			});

			// 更新任务状态为已完成
			await updateTaskAPI({
				projectId: projectId.value,
				id: taskId.value,
				status: TaskStatus.COMPLETED
			});

			hideLoading();
			showToast('保存成功', 'success');

			// 切换到结果选项卡
			activeTab.value = 'result';
		} catch (error : any) {
			hideLoading();
			console.error('保存失败:', error);
			showToast(error.message || '保存失败', 'error');
		}
	};

	// 获取主题样式
	const themeStyles = computed(() => getThemeStyles());

	// 容器背景样式
	const containerStyle = computed(() => ({
		background: themeStyles.value.bgGradient
	}));

	// ==================== 生命周期相关 ====================

	/**
	 * 初始化页面数据
	 * 在页面加载完成后执行初始计算
	 */
	const initializePageData = () : void => {
		performAllCalculations();
	};

	/**
	 * 页面加载时接收参数并加载数据
	 * 
	 * 执行流程：
	 * 1. 接收并转换projectId和taskId参数
	 * 2. 加载项目和任务数据
	 * 3. 尝试加载已保存的盈利预测数据
	 * 4. 如果任务未开始，标记为进行中
	 * 5. 执行初始计算
	 */
	onLoad(async (options : { projectId : number, taskId : number }) => {
		try {
			// 将URL参数从字符串转换为数字
			projectId.value = options.projectId;
			taskId.value = options.taskId;

			// 加载项目数据
			const projectRes = await getDetailAPI(projectId.value);
			projectName.value = projectRes.data.name;

			// 查找盈利预测任务
			const task = projectRes.data.tasks.find((t : any) => t.id === taskId.value);

			// 尝试加载已保存的盈利预测数据
			try {
				const predictionRes = await getProfitPredictionAPI(taskId.value);
				if (predictionRes.data) {
					// 将后端数据赋值给输入表单
					inputFormData.value = { ...predictionRes.data };
				}
			} catch (error) {
				// 暂无保存的数据，使用默认空表单
				console.log('暂无保存的数据');
			}

			// 如果任务未开始，标记为进行中
			if (task?.status === TaskStatus.NOT_STARTED) {
				await updateTaskAPI({
					projectId: projectId.value,
					id: taskId.value,
					status: TaskStatus.IN_PROGRESS
				});
			}

			// 执行初始计算
			initializePageData();
		} catch (error : any) {
			console.error('页面加载失败:', error);
			showToast(error.message || '加载失败', 'error');
		}
	});
</script>

<style lang="scss" scoped>
	/* 容器样式 */
	.profit-prediction-container {
		display: flex;
		flex-direction: column;
		/* background 由 containerStyle 动态设置 */
		height: 100vh;
		overflow: hidden;
		position: relative;

		/* 页面头部区域 */
		.page-header {
			padding: 24rpx 32rpx 20rpx;
			background: v-bind('themeStyles.bgCard');
			margin: 0 0 16rpx 0;
			border-bottom: 1rpx solid v-bind('themeStyles.borderLight');
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

			/* 项目信息提示栏 */
			.project-info-bar {
				margin-bottom: 20rpx;

				.project-info-content {
					display: flex;
					align-items: center;
					gap: 20rpx;
					padding: 24rpx 28rpx;
					background: linear-gradient(135deg, v-bind('themeStyles.accentBg') 0%, v-bind('themeStyles.bgCard') 100%);
					border-radius: 16rpx;
					border-left: 6rpx solid v-bind('themeStyles.primaryColor');
					box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);
					position: relative;
					overflow: hidden;

					&::before {
						content: '';
						position: absolute;
						top: -50%;
						right: -10%;
						width: 200rpx;
						height: 200rpx;
						background: v-bind('themeStyles.primaryColor');
						opacity: 0.05;
						border-radius: 50%;
					}

					.info-icon {
						font-size: 48rpx;
						width: 80rpx;
						height: 80rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						background: linear-gradient(135deg, v-bind('themeStyles.primaryColor') 0%, v-bind('themeStyles.accentColor') 100%);
						border-radius: 16rpx;
						box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.25);
						flex-shrink: 0;
					}

					.info-text {
						flex: 1;
						display: flex;
						flex-direction: column;
						gap: 6rpx;

						.project-label {
							font-size: 22rpx;
							font-weight: 500;
							color: v-bind('themeStyles.textTertiary');
							letter-spacing: 0.5rpx;
							text-transform: uppercase;
						}

						.project-name-text {
							font-size: 28rpx;
							color: v-bind('themeStyles.textPrimary');
							font-weight: 700;
							letter-spacing: 0.5rpx;
						}
					}
				}
			}

			/* 选项卡样式 */
			.tabs {
				display: flex;
				gap: 0;
				background: transparent;
				padding: 0;
				border-radius: 0;
				border: none;
				border-bottom: 2rpx solid v-bind('themeStyles.borderLight');

				.tab {
					flex: 1;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					padding: 0;
					background: transparent;
					border-radius: 0;
					transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
					position: relative;
					cursor: pointer;

					.tab-content {
						display: flex;
						align-items: center;
						gap: 12rpx;
						padding: 20rpx 16rpx;
						transition: all 0.3s ease;
					}

					.tab-icon {
						font-size: 40rpx;
						transition: all 0.3s ease;
						filter: grayscale(0.5);
					}

					.tab-text {
						font-size: 28rpx;
						font-weight: 500;
						color: v-bind('themeStyles.textTertiary');
						transition: all 0.3s ease;
					}

					.tab-indicator {
						position: absolute;
						bottom: -2rpx;
						left: 0;
						right: 0;
						height: 4rpx;
						background: v-bind('themeStyles.primaryGradient');
						border-radius: 2rpx 2rpx 0 0;
						animation: slideIn 0.3s ease;
					}

					&.active {
						.tab-icon {
							filter: grayscale(0);
							transform: scale(1.1);
						}

						.tab-text {
							color: v-bind('themeStyles.primaryColor');
							font-weight: 700;
						}
					}

					&:active {
						.tab-content {
							transform: scale(0.95);
						}
					}
				}
			}
		}

		@keyframes slideIn {
			from {
				transform: scaleX(0);
			}

			to {
				transform: scaleX(1);
			}
		}

		/* 输入区域包装器 */
		.input-wrapper {
			flex: 1;
			height: 0;
			display: flex;
			flex-direction: column;
			gap: 24rpx;

			/* 卡片样式 */
			.section-card {
				background: v-bind('themeStyles.bgCard');
				border-radius: 24rpx;
				padding: 32rpx;
				box-shadow: v-bind('themeStyles.cardBoxShadow');
				transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
				border: 1rpx solid v-bind('themeStyles.borderLight');
				margin: 20px;

				&:active {
					box-shadow: v-bind('themeStyles.hoverBoxShadow');
					transform: translateY(-2rpx);
				}

				/* 卡片头部 */
				.section-header {
					display: flex;
					align-items: center;
					margin-bottom: 32rpx;
					padding-bottom: 24rpx;
					border-bottom: 1rpx solid v-bind('themeStyles.borderLight');

					.icon-container {
						width: 88rpx;
						height: 88rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						border-radius: 20rpx;
						background: v-bind('themeStyles.primaryGradient');
						box-shadow: v-bind('themeStyles.buttonBoxShadow');
						font-size: 40rpx;
						margin-right: 24rpx;
					}

					.section-title {
						color: v-bind('themeStyles.textPrimary');
						font-size: 32rpx;
						font-weight: 700;
						letter-spacing: 0.5rpx;
						flex: 1;
					}

					.summary-value {
						color: v-bind('themeStyles.primaryColor');
						font-size: 32rpx;
						font-weight: 700;
						letter-spacing: -0.5rpx;
						text-align: right;
					}
				}

				/* 输入组 */
				.input-group {
					display: flex;
					flex-direction: column;
					gap: 24rpx;

					.input-field {
						display: flex;
						flex-direction: column;
						gap: 12rpx;

						.field-label {
							color: v-bind('themeStyles.textSecondary');
							font-size: 28rpx;
							font-weight: 600;
							letter-spacing: 0.5rpx;
						}

						.form-input {
							width: 100%;
							height: 88rpx;
							padding: 0 28rpx;
							border: 2rpx solid v-bind('themeStyles.border');
							border-radius: 16rpx;
							font-size: 30rpx;
							font-weight: 500;
							color: v-bind('themeStyles.textPrimary');
							box-sizing: border-box;
							background: v-bind('themeStyles.bgSecondary');
							transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
							line-height: 88rpx;

							&:focus {
								border-color: v-bind('themeStyles.primaryColor');
								outline: none;
								background: v-bind('themeStyles.bgCard');
								box-shadow: v-bind('themeStyles.focusBoxShadow');
								transform: translateY(-2rpx);
							}
						}

						.field-tip {
							color: v-bind('themeStyles.textPlaceholder');
							font-size: 24rpx;
							margin-top: 4rpx;
							line-height: 1.5;
						}
					}
				}

				/* 两列网格输入组 */
				.summary-row {
					display: flex;
					justify-content: space-between;
					background-color: v-bind('themeStyles.bgSecondary');
					border-radius: 8px;
					padding: 16px;
					margin: 12px 0;
				}

				.summary-item {
					display: flex;
					flex-direction: column;
					align-items: center;
					flex: 1;
				}

				.summary-label {
					font-size: 14px;
					color: v-bind('themeStyles.textTertiary');
					margin-bottom: 8px;
				}

				.summary-value {
					font-size: 18px;
					font-weight: bold;
					color: v-bind('themeStyles.primaryColor');
					text-align: center;
				}

				.input-group-grid {
					display: grid;
					grid-template-columns: 1fr 1fr;
					gap: 24rpx;

					.input-field {
						display: flex;
						flex-direction: column;
						gap: 12rpx;

						.field-label {
							color: v-bind('themeStyles.textSecondary');
							font-size: 26rpx;
							font-weight: 600;
							letter-spacing: 0.5rpx;
						}

						.form-input {
							width: 100%;
							height: 80rpx;
							padding: 0 24rpx;
							border: 2rpx solid v-bind('themeStyles.border');
							border-radius: 16rpx;
							font-size: 28rpx;
							font-weight: 500;
							color: v-bind('themeStyles.textPrimary');
							box-sizing: border-box;
							background: v-bind('themeStyles.bgSecondary');
							transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
							line-height: 80rpx;

							&:focus {
								border-color: v-bind('themeStyles.primaryColor');
								outline: none;
								background: v-bind('themeStyles.bgCard');
								box-shadow: v-bind('themeStyles.focusBoxShadow');
								transform: translateY(-2rpx);
							}
						}
					}
				}

				/* 错误提示信息 */
				.error-message {
					display: flex;
					align-items: center;
					padding: 20rpx 24rpx;
					background: #fee;
					border: 2rpx solid #f5222d;
					border-radius: 12rpx;
					margin-bottom: 24rpx;
					animation: shake 0.3s ease-in-out;

					.error-icon {
						font-size: 32rpx;
						margin-right: 12rpx;
					}

					.error-text {
						flex: 1;
						font-size: 26rpx;
						color: #f5222d;
						font-weight: 600;
						line-height: 1.5;
					}
				}

				/* 品类表格 */
				.category-table {
					width: 100%;
					margin-bottom: 24rpx;
					background: v-bind('themeStyles.bgSecondary');
					border-radius: 16rpx;
					padding: 24rpx;

					.table-header,
					.table-row {
						display: flex;
						border-bottom: 2rpx solid v-bind('themeStyles.border');

						.table-cell {
							flex: 1;
							font-size: 26rpx;
							display: flex;
							align-items: center;
							color: v-bind('themeStyles.textSecondary');
							font-weight: 600;
						}

						.table-input {
							flex: 1;
							height: 64rpx;
							padding: 0 20rpx;
							border: 2rpx solid v-bind('themeStyles.border');
							border-radius: 12rpx;
							font-size: 26rpx;
							font-weight: 500;
							text-align: center;
							background: v-bind('themeStyles.bgCard');
							color: v-bind('themeStyles.textPrimary');
							transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
							box-sizing: border-box;
							box-shadow: inset 0 2rpx 6rpx rgba(0, 0, 0, 0.02);
							line-height: 64rpx;

							&:focus {
								border-color: v-bind('themeStyles.primaryColor');
								outline: none;
								box-shadow: v-bind('themeStyles.focusBoxShadow'), inset 0 2rpx 6rpx rgba(0, 0, 0, 0.02);
							}

							&::placeholder {
								color: v-bind('themeStyles.textPlaceholder');
								font-size: 24rpx;
							}

							/* 错误状态样式 */
							&.input-error {
								border-color: #f5222d !important;
								background: #fff1f0;
								box-shadow: 0 0 0 2rpx rgba(245, 34, 45, 0.1), inset 0 2rpx 6rpx rgba(245, 34, 45, 0.05);
							}
						}
					}

					.table-header {
						font-weight: 700;
						color: v-bind('themeStyles.textPrimary');
						padding-bottom: 20rpx;
						margin-bottom: 16rpx;
						background: transparent;
					}

					.table-row {
						padding: 20rpx 0;
						background: transparent;

						&:last-child {
							border-bottom: none;
						}
					}
				}

				/* 品类统计摘要 */
				.category-summary {
					background: v-bind('themeStyles.accentBg');
					border-radius: 16rpx;
					padding: 28rpx;
					border: 2rpx solid v-bind('themeStyles.accentBorder');
					display: flex;
					justify-content: space-between;
					margin-top: 24rpx;

					.summary-item {
						display: flex;
						flex-direction: column;
						align-items: center;
						gap: 8rpx;
						font-size: 26rpx;
						color: v-bind('themeStyles.textSecondary');

						.summary-value {
							font-weight: 700;
							font-size: 32rpx;
							color: v-bind('themeStyles.primaryColor');
						}
					}
				}
			}

			/* 按钮组 */
			.btn-group {
				display: flex;
				gap: 20rpx;
				margin-top: 32rpx;

				.btn {
					flex: 1;
					padding: 28rpx 32rpx;
					border-radius: 16rpx;
					font-size: 28rpx;
					font-weight: 600;
					text-align: center;
					transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
					border: none;
					line-height: 1.5;
					display: flex;
					align-items: center;
					justify-content: center;
					position: relative;
					overflow: hidden;
					white-space: nowrap;
					box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);

					&::before {
						content: '';
						position: absolute;
						top: 50%;
						left: 50%;
						width: 0;
						height: 0;
						border-radius: 50%;
						background: rgba(255, 255, 255, 0.3);
						transform: translate(-50%, -50%);
						transition: width 0.6s, height 0.6s;
					}

					&:active::before {
						width: 300rpx;
						height: 300rpx;
					}

					&.btn-primary {
						background: v-bind('themeStyles.primaryGradient');
						color: white;
						box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.35);

						&:active {
							transform: translateY(2rpx);
							box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.25);
						}
					}

					&.btn-secondary {
						background: white;
						color: v-bind('themeStyles.primaryColor');
						border: 2rpx solid v-bind('themeStyles.primaryColor');
						box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.15);

						&::before {
							background: v-bind('themeStyles.primaryColor');
							opacity: 0.1;
						}

						&:active {
							background: v-bind('themeStyles.accentBg');
							transform: translateY(2rpx);
							box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.1);
						}
					}

					&.btn-info {
						background: linear-gradient(135deg, v-bind('themeStyles.infoColor') 0%, v-bind('themeStyles.primaryColor') 100%);
						color: white;
						box-shadow: 0 4rpx 16rpx rgba(59, 130, 246, 0.35);

						&:active {
							transform: translateY(2rpx);
							box-shadow: 0 2rpx 8rpx rgba(59, 130, 246, 0.25);
						}
					}
				}
			}
		}

		/* 结果区域 */
		.results-section {
			flex: 1;
			height: 0;

			/* 盈亏平衡分析结果展示区域 */
			.result-card {
				background: v-bind('themeStyles.bgCard');
				border-radius: 24rpx;
				padding: 40rpx;
				margin-bottom: 24rpx;
				box-shadow: v-bind('themeStyles.cardBoxShadow');
				border: 1rpx solid v-bind('themeStyles.borderLight');
				margin: 20px;

				.result-header {
					text-align: center;
					margin-bottom: 40rpx;
					padding-bottom: 32rpx;
					border-bottom: 1rpx solid v-bind('themeStyles.borderLight');
					position: relative;

					&::after {
						content: '';
						position: absolute;
						bottom: -2rpx;
						left: 50%;
						transform: translateX(-50%);
						width: 120rpx;
						height: 4rpx;
						background: v-bind('themeStyles.primaryGradient');
						border-radius: 2rpx;
					}

					.result-title {
						font-size: 36rpx;
						font-weight: 700;
						background: v-bind('themeStyles.primaryGradient');
						-webkit-background-clip: text;
						-webkit-text-fill-color: transparent;
						background-clip: text;
						letter-spacing: 1rpx;
					}
				}

				.result-content {
					.result-grid {
						display: grid;
						grid-template-columns: 1fr 1fr;
						gap: 24rpx;

						.result-item {
							display: flex;
							flex-direction: column;
							align-items: center;
							padding: 32rpx;
							background: v-bind('themeStyles.accentBg');
							border-radius: 20rpx;
							border: 2rpx solid v-bind('themeStyles.accentBorder');
							transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
							position: relative;
							overflow: hidden;

							&::before {
								content: '';
								position: absolute;
								top: 0;
								left: 0;
								right: 0;
								height: 6rpx;
								background: v-bind('themeStyles.primaryGradient');
							}

							&:active {
								transform: scale(0.98);
							}

							.result-label {
								font-size: 26rpx;
								color: v-bind('themeStyles.textSecondary');
								display: block;
								margin-bottom: 20rpx;
								font-weight: 600;
								text-align: center;
							}

							.result-value {
								font-size: 48rpx;
								font-weight: 800;
								color: v-bind('themeStyles.primaryColor');
								background: v-bind('themeStyles.primaryGradient');
								-webkit-background-clip: text;
								-webkit-text-fill-color: transparent;
								background-clip: text;
								letter-spacing: -1rpx;
								display: block;
								text-align: center;
								line-height: 1.2;
								margin-bottom: 16rpx;

								/* 为不支持background-clip的浏览器提供后备 */
								@supports not (background-clip: text) {
									-webkit-text-fill-color: v-bind('themeStyles.primaryColor');
								}
							}

							.result-note {
								font-size: 22rpx;
								color: v-bind('themeStyles.textSecondary');
								line-height: 1.5;
								display: block;
								text-align: center;
								opacity: 0.8;
							}

							.highlight-warning {
								color: v-bind('themeStyles.errorColor') !important;
								font-weight: bold !important;
							}
						}
					}
				}
			}

			/* 高亮卡片 */
			.highlight-card {
				background: linear-gradient(135deg, v-bind('themeStyles.bgCard') 0%, v-bind('themeStyles.accentBg') 100%);
				border: 1rpx solid v-bind('themeStyles.borderLight');
			}

			/* 投资回报分析卡片 */
			.investment-card {
				.investment-total {
					text-align: center;
					padding: 40rpx 32rpx;
					background: v-bind('themeStyles.accentBg');
					border-radius: 20rpx;
					margin-bottom: 32rpx;
					border: 2rpx solid v-bind('themeStyles.accentBorder');

					.investment-label {
						display: block;
						font-size: 28rpx;
						color: v-bind('themeStyles.textSecondary');
						font-weight: 600;
						margin-bottom: 16rpx;
					}

					.investment-amount {
						display: block;
						font-size: 56rpx;
						font-weight: 800;
						background: v-bind('themeStyles.primaryGradient');
						-webkit-background-clip: text;
						-webkit-text-fill-color: transparent;
						background-clip: text;
						letter-spacing: -1rpx;
					}
				}

				.investment-breakdown {
					display: flex;
					flex-direction: column;
					gap: 16rpx;

					.breakdown-item {
						display: flex;
						align-items: center;
						gap: 20rpx;
						padding: 24rpx;
						background: v-bind('themeStyles.bgSecondary');
						border-radius: 16rpx;
						transition: all 0.3s ease;
						border: 1rpx solid v-bind('themeStyles.borderLight');

						&:active {
							transform: scale(0.98);
							background: v-bind('themeStyles.accentBg');
						}

						.breakdown-icon {
							font-size: 40rpx;
							width: 64rpx;
							height: 64rpx;
							display: flex;
							align-items: center;
							justify-content: center;
							background: v-bind('themeStyles.bgCard');
							border-radius: 12rpx;
							flex-shrink: 0;
						}

						.breakdown-content {
							flex: 1;
							display: flex;
							flex-direction: column;
							gap: 6rpx;

							.breakdown-label {
								font-size: 26rpx;
								color: v-bind('themeStyles.textSecondary');
								font-weight: 600;
							}

							.breakdown-value {
								font-size: 32rpx;
								font-weight: 700;
								color: v-bind('themeStyles.textPrimary');
							}
						}

						.breakdown-percent {
							padding: 8rpx 20rpx;
							background: v-bind('themeStyles.primaryGradient');
							border-radius: 20rpx;
							flex-shrink: 0;

							.percent-text {
								font-size: 24rpx;
								font-weight: 700;
								color: white;
							}
						}
					}
				}
			}

			/* 结果值样式变体 */
			.large-value {
				font-size: 56rpx !important;
			}

			.success-value {
				color: #10b981 !important;
			}

			.warning-value {
				color: #f59e0b !important;
			}

			.danger-value {
				color: #ef4444 !important;
			}

			.highlight-value {
				background: v-bind('themeStyles.primaryGradient');
				-webkit-background-clip: text;
				-webkit-text-fill-color: transparent;
				background-clip: text;
				font-weight: 800;
			}

			/* 四列网格布局 */
			.four-column {
				grid-template-columns: repeat(2, 1fr) !important;
			}

			/* 客流对比分析卡片 */
			.customer-flow-card {
				.flow-achievement-wrapper {
					background: v-bind('themeStyles.accentBg');
					border-radius: 16rpx;
					padding: 32rpx;
					margin-bottom: 32rpx;

					.achievement-header {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-bottom: 20rpx;

						.achievement-label {
							font-size: 28rpx;
							color: v-bind('themeStyles.textSecondary');
							font-weight: 600;
						}

						.achievement-value {
							font-size: 48rpx;
							font-weight: 800;
							letter-spacing: -1rpx;
						}
					}

					.achievement-bar {
						height: 24rpx;
						background: v-bind('themeStyles.bgCard');
						border-radius: 12rpx;
						overflow: hidden;
						margin-bottom: 20rpx;

						.achievement-fill {
							height: 100%;
							border-radius: 12rpx;
							transition: width 0.8s cubic-bezier(0.4, 0, 0.2, 1);
						}
					}

					.achievement-status {
						display: flex;
						align-items: center;
						justify-content: center;
						gap: 12rpx;

						.status-icon {
							font-size: 32rpx;
						}

						.status-text {
							font-size: 28rpx;
							font-weight: 600;
						}
					}
				}

				.flow-comparison {
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-bottom: 32rpx;

					.flow-item {
						flex: 1;
						display: flex;
						flex-direction: column;
						align-items: center;
						gap: 12rpx;

						.flow-label {
							font-size: 26rpx;
							color: v-bind('themeStyles.textSecondary');
							font-weight: 600;
						}

						.flow-value {
							font-size: 40rpx;
							font-weight: 800;
							color: v-bind('themeStyles.textPrimary');

							&.primary {
								background: v-bind('themeStyles.primaryGradient');
								-webkit-background-clip: text;
								-webkit-text-fill-color: transparent;
								background-clip: text;
							}
						}
					}

					.flow-divider {
						padding: 0 24rpx;

						.vs-text {
							font-size: 24rpx;
							font-weight: 700;
							color: v-bind('themeStyles.textTertiary');
							padding: 8rpx 16rpx;
							background: v-bind('themeStyles.accentBg');
							border-radius: 20rpx;
						}
					}
				}

				.flow-gap {
					background: linear-gradient(135deg, #fef3c7 0%, #fed7aa 100%);
					border-left: 6rpx solid #f59e0b;
					padding: 24rpx 32rpx;
					border-radius: 0 16rpx 16rpx 0;
					display: flex;
					flex-direction: column;
					gap: 8rpx;

					&.surplus {
						background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%);
						border-left-color: #10b981;
					}

					.gap-label {
						font-size: 24rpx;
						color: #92400e;
						font-weight: 600;
					}

					.gap-value {
						font-size: 36rpx;
						font-weight: 800;
						color: #78350f;
					}

					.gap-note {
						font-size: 24rpx;
						color: #92400e;
						line-height: 1.6;
					}

					&.surplus {

						.gap-label,
						.gap-value,
						.gap-note {
							color: #065f46;
						}

						.gap-value {
							color: #064e3b;
						}
					}
				}
			}

			/* 预期盈利分析卡片 */
			.profit-forecast-card {
				.roi-analysis {
					margin-top: 32rpx;
					padding-top: 32rpx;
					border-top: 1rpx solid v-bind('themeStyles.borderLight');
					display: flex;
					justify-content: space-around;
					gap: 32rpx;

					.roi-item {
						flex: 1;
						display: flex;
						flex-direction: column;
						align-items: center;
						gap: 12rpx;
						padding: 24rpx;
						background: v-bind('themeStyles.accentBg');
						border-radius: 16rpx;

						.roi-label {
							font-size: 26rpx;
							color: v-bind('themeStyles.textSecondary');
							font-weight: 600;
						}

						.roi-value {
							font-size: 36rpx;
							font-weight: 800;
							background: v-bind('themeStyles.primaryGradient');
							-webkit-background-clip: text;
							-webkit-text-fill-color: transparent;
							background-clip: text;
						}
					}
				}

				.highlight-success {
					background: linear-gradient(135deg, #d1fae5 0%, #a7f3d0 100%) !important;
					border-color: #10b981 !important;
				}

				.highlight-danger {
					background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%) !important;
					border-color: #ef4444 !important;
				}
			}

			/* 经营能力评估卡片样式 */
			.assessment-card {
				.assessment-content {
					padding: 0;

					.assessment-level {
						display: flex;
						justify-content: space-between;
						align-items: center;
						padding: 32rpx;
						background: v-bind('themeStyles.accentBg');
						border-radius: 16rpx;
						margin-bottom: 32rpx;

						.level-label {
							font-size: 28rpx;
							color: v-bind('themeStyles.textSecondary');
							font-weight: 600;
						}

						.level-badge {
							display: flex;
							align-items: center;
							gap: 12rpx;
							padding: 16rpx 32rpx;
							border-radius: 50rpx;
							box-shadow: v-bind('themeStyles.buttonBoxShadow');

							.level-icon {
								font-size: 32rpx;
							}

							.level-text {
								font-size: 30rpx;
								font-weight: 700;
								color: white;
							}
						}
					}

					.assessment-details {
						display: flex;
						flex-direction: column;
						gap: 28rpx;

						.detail-item {
							display: flex;
							align-items: center;
							gap: 16rpx;

							.detail-label {
								font-size: 26rpx;
								color: v-bind('themeStyles.textSecondary');
								font-weight: 600;
								min-width: 120rpx;
							}

							.progress-bar {
								flex: 1;
								height: 20rpx;
								background: v-bind('themeStyles.bgSecondary');
								border-radius: 10rpx;
								overflow: hidden;
								position: relative;

								.progress-fill {
									height: 100%;
									border-radius: 10rpx;
									transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1);
								}
							}

							.detail-value {
								font-size: 26rpx;
								color: v-bind('themeStyles.textPrimary');
								font-weight: 700;
								min-width: 80rpx;
								text-align: right;
							}
						}
					}
				}
			}

			/* 品类结构分析样式 */
			.category-analysis {
				display: flex;
				flex-direction: column;
				gap: 20rpx;

				.category-row {
					background: v-bind('themeStyles.accentBg');
					border-radius: 16rpx;
					padding: 24rpx;
					border: 1rpx solid v-bind('themeStyles.borderLight');
					transition: all 0.3s ease;

					&:active {
						transform: scale(0.98);
						background: v-bind('themeStyles.bgSecondary');
					}

					.category-info {
						display: flex;
						justify-content: space-between;
						align-items: center;
						margin-bottom: 16rpx;

						.category-name {
							font-size: 28rpx;
							font-weight: 700;
							color: v-bind('themeStyles.textPrimary');
						}

						.category-ratio {
							font-size: 24rpx;
							color: v-bind('themeStyles.textSecondary');
							padding: 6rpx 16rpx;
							background: v-bind('themeStyles.bgCard');
							border-radius: 20rpx;
						}
					}

					.category-metrics {
						display: flex;
						gap: 12rpx;
						justify-content: space-between;

						.metric {
							flex: 1;
							display: flex;
							flex-direction: column;
							align-items: center;
							padding: 12rpx;
							background: v-bind('themeStyles.bgCard');
							border-radius: 12rpx;

							&.highlight {
								background: v-bind('themeStyles.primaryGradient');

								.metric-label,
								.metric-value {
									color: white;
								}
							}

							.metric-label {
								font-size: 22rpx;
								color: v-bind('themeStyles.textTertiary');
								margin-bottom: 8rpx;
							}

							.metric-value {
								font-size: 26rpx;
								font-weight: 700;
								color: v-bind('themeStyles.textPrimary');
							}
						}
					}
				}
			}

			/* 成本结构分析样式 */
			.cost-structure {
				display: flex;
				flex-direction: column;
				gap: 20rpx;

				.cost-row {
					display: flex;
					flex-direction: column;
					gap: 12rpx;
					padding: 20rpx;
					background: v-bind('themeStyles.accentBg');
					border-radius: 12rpx;
					border: 1rpx solid v-bind('themeStyles.borderLight');

					.cost-info {
						display: flex;
						justify-content: space-between;
						align-items: center;

						.cost-name {
							font-size: 26rpx;
							color: v-bind('themeStyles.textSecondary');
							font-weight: 600;
						}

						.cost-amount {
							font-size: 28rpx;
							font-weight: 700;
							color: v-bind('themeStyles.textPrimary');
						}
					}

					.cost-bar-wrapper {
						display: flex;
						align-items: center;
						gap: 16rpx;

						.cost-bar {
							flex: 1;
							height: 16rpx;
							background: v-bind('themeStyles.bgCard');
							border-radius: 8rpx;
							overflow: hidden;

							.cost-bar-fill {
								height: 100%;
								border-radius: 8rpx;
								transition: width 0.6s cubic-bezier(0.4, 0, 0.2, 1);
							}
						}

						.cost-percentage {
							font-size: 24rpx;
							color: v-bind('themeStyles.textPrimary');
							font-weight: 700;
							min-width: 80rpx;
							text-align: right;
						}
					}
				}
			}

			/* 经营建议区域 */
			.advice-card {
				background: v-bind('themeStyles.bgCard');
				border-radius: 24rpx;
				padding: 40rpx;
				margin-bottom: 24rpx;
				box-shadow: v-bind('themeStyles.cardBoxShadow');
				border: 1rpx solid v-bind('themeStyles.borderLight');

				&.enhanced-advice {
					.advice-content {
						.advice-section {
							margin-bottom: 32rpx;
							padding-bottom: 28rpx;
							border-bottom: 1rpx solid v-bind('themeStyles.borderLight');

							&:last-child {
								margin-bottom: 0;
								padding-bottom: 0;
								border-bottom: none;
							}

							.advice-section-title {
								font-size: 30rpx;
								font-weight: 700;
								color: v-bind('themeStyles.textPrimary');
								margin-bottom: 20rpx;
								display: block;
							}
						}
					}
				}

				.advice-header {
					display: flex;
					align-items: center;
					margin-bottom: 32rpx;
					padding-bottom: 24rpx;
					border-bottom: 1rpx solid v-bind('themeStyles.borderLight');

					.icon-container {
						width: 88rpx;
						height: 88rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						border-radius: 20rpx;
						background: v-bind('themeStyles.primaryGradient');
						box-shadow: v-bind('themeStyles.buttonBoxShadow');
						font-size: 40rpx;
						margin-right: 24rpx;
					}

					.advice-title {
						color: v-bind('themeStyles.textPrimary');
						font-size: 32rpx;
						font-weight: 700;
						letter-spacing: 0.5rpx;
					}
				}

				.advice-content {
					display: flex;
					flex-direction: column;
					gap: 20rpx;

					.advice-text {
						color: v-bind('themeStyles.textSecondary');
						font-size: 28rpx;
						line-height: 1.8;
						padding-left: 32rpx;
						position: relative;

						&::before {
							content: '•';
							position: absolute;
							left: 0;
							color: v-bind('themeStyles.primaryColor');
							font-size: 36rpx;
							font-weight: bold;
						}
					}
				}
			}

			/* 行业提醒 */
			.industry-tip {
				background: v-bind('themeStyles.bgCard');
				border: 1rpx solid v-bind('themeStyles.borderLight');
				border-left: 6rpx solid v-bind('themeStyles.warningColor');
				padding: 32rpx;
				border-radius: 0 20rpx 20rpx 0;
				margin-bottom: 24rpx;
				box-shadow: v-bind('themeStyles.cardBoxShadow');

				.tip-content {
					color: v-bind('themeStyles.textSecondary');
					font-size: 28rpx;
					line-height: 1.8;

					.tip-highlight {
						font-weight: 700;
						color: v-bind('themeStyles.warningColor');
						display: inline-block;
						margin-bottom: 8rpx;
					}
				}
			}

			/* 返回按钮组 */
			.btn-group {
				margin-top: 32rpx;

				.btn {
					width: 100%;
					padding: 28rpx 40rpx;
					border-radius: 16rpx;
					font-size: 28rpx;
					font-weight: 600;
					text-align: center;
					transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
					border: none;
					line-height: 1.5;
					display: flex;
					align-items: center;
					justify-content: center;
					position: relative;
					overflow: hidden;
					white-space: nowrap;

					&::before {
						content: '';
						position: absolute;
						top: 50%;
						left: 50%;
						width: 0;
						height: 0;
						border-radius: 50%;
						background: rgba(255, 255, 255, 0.3);
						transform: translate(-50%, -50%);
						transition: width 0.6s, height 0.6s;
					}

					&:active::before {
						width: 300rpx;
						height: 300rpx;
					}

					&.btn-secondary {
						background: white;
						color: v-bind('themeStyles.primaryColor');
						border: 2rpx solid v-bind('themeStyles.primaryColor');
						box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.15);

						&::before {
							background: v-bind('themeStyles.primaryColor');
							opacity: 0.1;
						}

						&:active {
							background: v-bind('themeStyles.accentBg');
							transform: translateY(2rpx);
							box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.1);
						}
					}

					&.btn-primary {
						background: v-bind('themeStyles.primaryGradient');
						color: white;
						box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.35);

						&:active {
							transform: translateY(2rpx);
							box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.25);
						}
					}
				}
			}
		}

		/* 页脚 */
		.footer {
			flex-shrink: 0;
			text-align: center;
			padding: 32rpx;
			background: transparent;
			margin-top: 16rpx;

			.footer-text {
				color: v-bind('themeStyles.textPlaceholder');
				font-size: 24rpx;
				letter-spacing: 0.5rpx;
				opacity: 0.8;
			}
		}
	}

	/* 响应式布局 */
	@media (max-width: 375px) {
		.profit-prediction-container {
			.tabs {
				padding: 16rpx 24rpx;
				gap: 12rpx;

				.tab {
					padding: 20rpx 12rpx;

					.tab-icon {
						font-size: 40rpx;
					}

					.tab-text {
						font-size: 24rpx;
					}
				}
			}

			.input-wrapper {
				padding: 0 24rpx 32rpx;
				gap: 20rpx;

				.section-card {
					padding: 24rpx;
					border-radius: 20rpx;

					.section-header {
						margin-bottom: 24rpx;

						.icon-container {
							width: 72rpx;
							height: 72rpx;
							font-size: 32rpx;
							margin-right: 20rpx;
						}

						.section-title {
							font-size: 28rpx;
						}

						.summary-value {
							font-size: 28rpx;
						}
					}

					.input-group-grid {
						gap: 20rpx;
					}
				}

				.btn-group {
					gap: 20rpx;
				}
			}

			.results-section {
				padding: 0 24rpx 32rpx;

				.result-card {
					padding: 32rpx;
					border-radius: 20rpx;

					.result-header {
						margin-bottom: 32rpx;

						.result-title {
							font-size: 32rpx;
						}
					}

					.result-content {
						.result-grid {
							gap: 20rpx;

							.result-item {
								padding: 24rpx;

								.result-label {
									font-size: 24rpx;
								}

								.result-value {
									font-size: 40rpx;
								}

								.result-note {
									font-size: 20rpx;
								}
							}
						}
					}
				}

				.advice-card {
					padding: 32rpx;

					.advice-header {
						.icon-container {
							width: 72rpx;
							height: 72rpx;
							font-size: 32rpx;
						}

						.advice-title {
							font-size: 28rpx;
						}
					}

					.advice-content {
						.advice-text {
							font-size: 26rpx;
						}
					}
				}

				.industry-tip {
					padding: 24rpx;

					.tip-content {
						font-size: 26rpx;
					}
				}
			}
		}
	}

	/* 抖动动画 */
	@keyframes shake {

		0%,
		100% {
			transform: translateX(0);
		}

		10%,
		30%,
		50%,
		70%,
		90% {
			transform: translateX(-5rpx);
		}

		20%,
		40%,
		60%,
		80% {
			transform: translateX(5rpx);
		}
	}
</style>